package online.sixfish.doubao.controller;

import cn.hutool.core.io.file.FileNameUtil;
import online.sixfish.common.api.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Collections;
import java.util.UUID;
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api")
public class FileUploadController {
    private static final String PATH="C:\\images\\";

    @PreAuthorize("hasAnyRole('user','admin')")
    @PostMapping("/upload")
    public ApiResult uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ApiResult.failed("图片为空");
        }

        String originalFilename = file.getOriginalFilename();
        String suffix = FileNameUtil.getSuffix(originalFilename);
        String newName = UUID.randomUUID() + "." + suffix;
        String filePath = PATH + newName;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
             log.info("文件上传失败,{}",e);
             return ApiResult.failed("上传失败！");
        }
        log.info("文件上传成功,{}",newName);
        return ApiResult.success(Collections.singletonMap("fileName",newName));
    }

    @PreAuthorize("hasAnyRole('user','admin')")
    @GetMapping("/preview")
    public ApiResult previewFileBase64(@RequestParam String fileName) {
        try {
            // 从本地路径中读取图片文件
            File file = new File(PATH + fileName);
            // 将图片文件转换为字节数组
            byte[] fileContent = FileUtils.readFileToByteArray(file);
            // 将字节数组转换为base64格式的字符串
            String base64Image = Base64.getEncoder().encodeToString(fileContent);

            // 返回base64格式的图片数据
            return ApiResult.success(Collections.singletonMap("base64",base64Image));
        } catch (IOException e) {
            log.info("e,{}", e);
            return ApiResult.failed();
        }
    }
    @GetMapping("/image/{imageName}")
    public ResponseEntity<InputStreamResource> getImage(@PathVariable String imageName) throws IOException {
        String imagePath = PATH + imageName;
        Path imageFilePath = Paths.get(imagePath);
        InputStream inputStream = Files.newInputStream(imageFilePath.toFile().toPath());
        InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(inputStreamResource);
    }

}
